package entity

import (
	"fmt"
	"time"

	"gorm.io/gorm"
	"shqsoft.cn/pas3ui/base"
)

//CompPhjr 小微普惠导入
type CompPhjr struct {
	ID   int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	EVNO string    `gorm:"column:EVNO"`
	JGDM string    `gorm:"column:JGDM"`
	CUNM string    `gorm:"column:CUNM"`
	DTID time.Time `gorm:"column:DTID"`
	JLID int       `gorm:"column:JLID"`
	CUID *int      `gorm:"column:CUID"`
}

//TableName
func (CompPhjr) TableName() string {
	return "T_COMP_PHJR"
}

// BeforeCreate
func (u *CompPhjr) BeforeCreate(tx *gorm.DB) (err error) {
	base.CHDB.Raw(`SELECT "JLID" FROM "T_CM_CORP_LOAN_DUBIL_SUM_M" WHERE "CRDT_DUBIL_NUM"=?`, u.EVNO).Row().Scan(&u.JLID)
	base.CHDB.Raw(`SELECT "CUID" FROM "T_CM_CORP_CUST_DIM" WHERE "ORG_ORG_CD"=?`, u.JGDM).Row().Scan(&u.CUID)
	if u.CUID == nil {
		base.CHDB.Raw(`SELECT "CUID" FROM "T_CM_CORP_CUST_DIM" WHERE "CUST_NAME" =?`, u.CUNM).Row().Scan(&u.CUID)
	}
	if u.CUID == nil {
		err = fmt.Errorf("客户名称%s或组织机构代码%s在系统中不存在！", u.CUNM, u.JGDM)
		return
	}
	//判断是否重复导入
	var count int
	if u.ID == 0 {
		tx.Raw(`SELECT COUNT(*) FROM "T_COMP_PHJR" WHERE "JLID"=? AND "DTID"=?`, u.JLID, u.DTID).Row().Scan(&count)
		if count > 0 {
			err = fmt.Errorf("借据编号:%s,不能重复导入！", u.EVNO)
			return
		}
	}
	return
}

// AfterCreate
func (u *CompPhjr) AfterCreate(tx *gorm.DB) (err error) {
	var (
		count          int
		sqlStr         string
		monthStartTime string
	)
	tx.Raw(`SELECT COUNT(*) FROM "T_COMP_PHJR_ZIPPER" WHERE "CUID"=? AND "EDATE"='2099-12-31'`, u.CUID).Row().Scan(&count)
	if count == 0 {
		monthStartTime, _ = base.GetQuarterDay(u.DTID)
		sqlStr = `INSERT INTO "T_COMP_PHJR_ZIPPER"("JLID", "CUID","SDATE", "EDATE", "ISPH") VALUES(?, ?,?, '2099-12-31', 1)`
		err = tx.Exec(sqlStr, u.JLID, u.CUID, monthStartTime).Error
		if err != nil {
			return err
		}
	}
	return
}

//CompPhjrEF 返回结构体
func CompPhjrEF() base.EntityFunc {
	return func() interface{} {
		entity := CompPhjr{}
		return &entity
	}
}

//CompPhjrESF 返回结构体数组
func CompPhjrESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []CompPhjr
		return &entities
	}
}

func CompPhjrAfterImport(tx *gorm.DB, params map[string]string) (err error) {
	dateStr := params["DTID"][:8] + "01"
	dtid, _ := time.Parse("2006-01-02", dateStr)
	dtid = dtid.AddDate(0, -1, 0)
	monthEndTime, _ := base.GetQuarterDay(dtid)
	sqlStr := `UPDATE "T_COMP_LSDK_ZIPPER" SET "EDATE"=? WHERE "EDATE"='2099-12-31' AND "SDATE"<?`
	err = tx.Exec(sqlStr, monthEndTime, dateStr).Error
	if err != nil {
		return err
	}
	tx.Commit()
	base.CHDB.Exec("system reload dictionary pas_olap_nj.DICT_COMP_PHJR_ZIPPER")
	return
}

func init() {
	base.SetAfterCallBack("CompPhjr", CompPhjrAfterImport)
	base.DaoPoolObj.Put("CompPhjr", base.NewDefaultDao(CompPhjrEF(), CompPhjrESF(), nil, "my"))
}
